//包含n个reducer函数：根据老的state和指定的action，返回一个新的state

import { combineReducers } from 'redux'
import { AUTH_SUCCESS, ERROR_MSG, RECEIVE_USER, RESET_USER, RECEIVE_USERLIST, RECEIVE_MSG_LIST, RECEIVE_MSG, MSG_READ } from './action-types'
import { getRedirectTo } from '../utils'

const initUser = {
    username: '',//用户名
    type: '',//用户类型
    msg: '',//错误提示信息
    redirectTo: ''//指定需要自动重定向的路由路径
}
//产生user状态的reducer
function user(state = initUser, action) {
    switch (action.type) {
        case AUTH_SUCCESS://data是user
            const { type, header } = action.data
            return { ...action.data, redirecTo: getRedirectTo(type, header) }
        case ERROR_MSG://data是msg
            return { ...state, msg: action.data }
        case RECEIVE_USER://data是user
            return action.data
        case RESET_USER://data是msg
            return { ...initUser, msg: action.data }
        default:
            return state
    }
}

const initUserList = []
//产生userlist状态的reducer
function userlist(state = initUserList, action) {
    switch (action.type) {
        case RECEIVE_USERLIST://data为userlist
            return action.data
        default:
            return state
    }
}


const initChat = {
    users: {},//所有用户信息的对象，属性名userid，属性值是{username,header} 
    chatMsgs: [],//当前用户所有相关msg数组
    unReadCount: 0 //总的未读数量
}
//产生聊天状态的reducer
function chat(state = initChat, action) {
    switch (action.type) {
        case RECEIVE_MSG_LIST:
            const { users, chatMsgs, userid } = action.data
            return {
                users,
                chatMsgs,
                unReadCount: chatMsgs.reduce((preTotal, msg) => preTotal + (
                    !msg.read && msg.to === userid ? 1 : 0
                ), 0)
            }
        case RECEIVE_MSG://data: chatMsg
            const { chatMsg } = action.data
            return {
                users: state.users,
                chatMsgs: [...state.chatMsgs, chatMsg],
                unReadCount: state.unReadCount + (!chatMsg.read && chatMsg.to === action.data.userid ? 1 : 0)
            }
        case MSG_READ:
            const { from, to, count } = action.data
            return {
                users: state.users,
                chatMsgs: state.chatMsgs.map(msg => {
                    if (msg.from === from && msg.to === to && !msg.read) {//需要更新的
                        return  {...msg,read:true}
                    } else {//不需要
                        return msg
                    }
                }),
                unReadCount: state.unReadCount - count
            }
        default:
            return state
    }
}

export default combineReducers({
    user,
    userlist,
    chat
})



//向外暴露的状态的结构:{user:{}}

/*
用户主界面路由
    zhuren:/zhuren
    customer:/customer
用户信息完善界面路由
    zhuren:/zhureninfo
    customer:/customerinfo
判断是否已经完善信息 user.header是否有值
判断用户类型：看user.type
*/
//返回对应的路由路径
